<?php
class RedisModel {

    protected $redis ='';
    protected $redis_host = "localhost";
    protected $redis_port = "6379";
    protected $redis_auth = "";
    protected $redis_db = "0";


//    protected $redis ='';
//    protected $redis_host = "r-uf6nnkxjjo46g2cl61.redis.rds.aliyuncs.com";
//    protected $redis_port = "6379";
//    protected $redis_auth = "HH61redis14";
//    protected $redis_db = "0";


    function __construct(){
//        $redis_config_obj = Yaf_Registry::get("config")->get('common.redis')->toarray();
        $this->redis = new Redis();
        //连接服务器
        $this->redis->connect($this->redis_host);
        //授权
        $this->redis->auth($this->redis_auth);
        $this->redis->select($this->redis_db);
    }

    function getData($key) {
        $value = $this->redis->get($key);
        $value_serl = @unserialize($value);
        if(is_object($value_serl) || is_array($value_serl)){
            return $value_serl;
        }
        return $value;
    }
    function getList($key) {
        return $this->redis->LRANGE($key, 0, -1);
    }
    function getSize($key) {
        $size = $this->redis->llen($key);
        if(!empty($size)) {
            return intval($size) ;
        } else {
            return 0;
        }

    }

    function delData($key) {
        return $this->redis->del($key);
    }
    function setData($key, $val, $expire = 0) {
        if(empty($expire)) {
            $expire =  3600;
        }
        if(is_object($val) || is_array($val)){
            $val = serialize($val);
        }
        return $this->redis->setex($key, $expire, $val);
    }
    function setExpireData($key, $val, $expire = 0) {
        if(empty($expire)) {
            $expire =  3600;
        }else{
            $expire = $expire - time();
        }
        if($expire < 0 ){
            $expire = 0;
        }
        if(is_object($val) || is_array($val)){
            $val = serialize($val);
        }
        return $this->redis->setex($key, $expire, $val);
    }
    function ttl($key) {
        return $this->redis->ttl($key);
    }
    function lpush($key, $val) {
        return $this->redis->lPush($key, $val);
    }
    function rPush($key, $val) {
        return $this->redis->rPush($key, $val);
    }
    function lpop($key) {
        return $this->redis->lpop($key);
    }
    function rpop($key) {
        return $this->redis->rpop($key);
    }

    function expire($key, $tmout)
    {
        return $this->redis->expire($key, $tmout);
    }
    function lSize($key){
        return $this->redis->llen($key);
    }
    function llen($key){
        return $this->redis->llen($key);
    }
    function sadd($key, $val) {
        return $this->redis->sadd($key, $val);
    }
}